package com.chen.aop;
import com.chen.mapper.OperateLogMapper;
import com.chen.pojo.OperateLog;
import com.chen.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.chen.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取操作人ID，这里假设通过某种方式获取
        Integer operateEmpId = getCurrentEmpId();

        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = signature.getDeclaringTypeName();
        String methodName = signature.getName();

        // 记录开始时间
        LocalDateTime startTime = LocalDateTime.now();

        // 获取方法参数
        String methodParams = Arrays.toString(joinPoint.getArgs());

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 记录结束时间
        LocalDateTime endTime = LocalDateTime.now();

        // 计算方法执行耗时
        Long costTime = java.time.Duration.between(startTime, endTime).toMillis();

        // 封装日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(operateEmpId);
        operateLog.setOperateTime(startTime);
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        operateLog.setReturnValue(result == null ? "" : result.toString());
        operateLog.setCostTime(costTime);

        // 插入日志
        log.info("记录日志：{}", operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    // 假设通过某种方式获取当前操作人ID
    private Integer getCurrentEmpId() {
        // 这里可以替换为实际获取操作人ID的逻辑
        return CurrentHolder.getCurrentId();
    }
}
